import { moduleGetApi } from '@/manager-core/api/module/module'

const state = {
  init: false,
  datas : {},
  code: "code12" 
}

// getters
const getters = {
  menus: (state:any, getters:any, rootState:any) => {
    return state.datas;
  },
  code: (state:any, getters:any, rootState:any) => {
    return state.code;
  }
}

// actions
const actions = {
  loadMenu ({ state, commit }:any) {
      return new Promise((resolve,reject) =>{
        // console.log("VUEX loadMenu " , state.init)
        if(!state.init){
          // console.log("VUX LOADMENU SUCCEED")
            moduleGetApi()
            .then((r:any)=>{
              // console.log("Get Menu ", r);
              commit("setMenus",r);
              commit("setInit",true);
              resolve(r)
            })
            .catch((e:any)=>{
              commit("clear");
              reject(e);
            })
        }
        else {
          console.log("VUX not need reload")
          resolve("true")
        }
    })
  },

  reload({state,dispatch,commit}:any){
    return new Promise((resolve,reject)=>{
      commit("clear");
      return dispatch("loadMenu");
    })
  },

  clear ({ state, commit }:any) {
    commit("clear");
  }
}

// mutations
const mutations = {
  setMenus (state:any, payload:any) {
    console.log("store save menus",payload)
    state.datas = payload;
  },

  setInit(state:any){
    state.init = state;
  },

  clear (state:any) {
    state.init = false;
    state.datas = [];
  },

}

export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations
}